package com.dlc.shop.wukongim.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.dlc.shop.common.exception.YamiShopBindException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * 悟空im配置中心
 * @author TRACK
 */
@Configuration
public class WuKongImConfig {
    private static final Logger logger = LoggerFactory.getLogger(WuKongImConfig.class);

    @Value("${wukongim.address}")
    private String address;

    @Value("${wukongim.token:}")
    private String token;

    public Boolean post(String url, Object obj) {
        HttpResponse httpResponse = doPost(url, obj);
        if (Objects.equals(httpResponse.getStatus(), HttpStatus.HTTP_OK)) {
            return true;
        }
        throw new YamiShopBindException(httpResponse.body());
    }

    public <T> T post(String url, Object obj, Class<T> clazz) {
        HttpResponse httpResponse = doPost(url, obj);
        if (!Objects.equals(httpResponse.getStatus(), HttpStatus.HTTP_OK)) {
            throw new YamiShopBindException("请求异常");
        }
        return JSON.parseObject(httpResponse.body(), clazz);
    }

    private HttpResponse doPost(String url, Object obj) {
        HttpRequest httpRequest = HttpRequest.post(address + url);
        if (StrUtil.isNotBlank(token)) {
            // 具体配置在wk.yaml中的managerToken
            httpRequest.header("token", token);
        }
        HttpResponse httpResponse = httpRequest.body(JSON.toJSONString(obj)).execute();
        return httpResponse;
    }
}
